package cn.kgc.service.impl;

import cn.kgc.entity.RoleInfo;
import cn.kgc.entity.UserInfo;
import cn.kgc.entity.UserRole;
import cn.kgc.mapper.RoleMapper;
import cn.kgc.mapper.UserMapper;
import cn.kgc.mapper.UserRoleMapper;
import cn.kgc.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl  implements UserService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public UserInfo login(String username, String password) {
        Example example = new Example(UserInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        criteria.andEqualTo("psw",password);
        UserInfo userInfo = userMapper.selectOneByExample(example);
        return userInfo;
    }

    @Override
    public Page<List<UserInfo>> getUser(Integer pageNo, Integer pageSize, String name) {
        PageHelper.startPage(pageNo,pageSize);
        Page<List<UserInfo>> page = (Page) userMapper.selectAll();
        return page;
    }
//增加用户
    @Override
    public void addUser(UserInfo userInfo) {
        System.out.println("auth:"+userInfo.getAuths());
        userMapper.insert(userInfo);
        UserRole  userRole =
                new UserRole(null,userInfo.getId(), Integer.parseInt(userInfo.getAuths()));
        userRoleMapper.insert(userRole);
    }


    @Override
    public UserInfo getRoleById(Integer id) {
        UserInfo userInfo=  userMapper.selectByPrimaryKey(id);
        //System.out.println(userInfo.getId()+"用户是"+userInfo);
        UserRole userRole= userRoleMapper.getRidByUid(userInfo.getId());
        RoleInfo roleInfo = roleMapper.selectByPrimaryKey(userRole.getRoleId());
        roleInfo.setText(roleInfo.getRoleName());
        userInfo.setAuths(roleInfo.getText());
        return userInfo;
    }
    //删除用户
    @Override
    public void deleteUser(String ids) {
        String[] idsArr = ids.split(",");
        for (String id : idsArr){
            userMapper.deleteByPrimaryKey(id);
           userRoleMapper.deleteUR(Integer.parseInt(id));
        }

    }




}
